﻿/*
   Created 2009 December 6, Randall Maas
   Copyright (c) 2009, Randall Maas
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

   Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

   Neither the name of Blackwood Designs, LLC nor the names of its contributors
   may be used to endorse or promote products derived from this software without
   specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
   THE POSSIBILITY OF SUCH DAMAGE.
*/



using System;
using System . Collections . Generic;
using System . Drawing;
using System . Runtime . InteropServices;
using System . Runtime . InteropServices.ComTypes;
using System . Windows. Forms; 

public partial class DirectShowNode : IDisposable
{
   /// <summary>
   /// This maps the device path to our local camera object
   /// </summary>
   static Dictionary<string,DirectShowNode> AudioDevs = new Dictionary<string,DirectShowNode>();

   /// <summary>
   /// This is used to enumerate all of the Audio Input devices that the system knows about
   /// </summary>
   /// <returns>An enumeration of the video input devices</returns>
   static public IEnumerable<DirectShowNode> AudioDevices()
   {
      IEnumMoniker En = DeviceEnum(ref DirectShowNode . CLSID_AudioInputDeviceCategory);
      if (null == En)
        yield break;

      foreach (IMoniker Moniker in COM . Enumerator(En))
      {
         DirectShowNode S = new DirectShowNode(Moniker), T;
         string Key = S . DevicePath;
         if (null == Key)
           Key = S . DisplayName;
         if (AudioDevs . TryGetValue(Key, out T))
           {
              S . Dispose();
              S = T;
           }
          else
           AudioDevs[Key] = S;

         yield return S;
      }

      Marshal . ReleaseComObject(En);
   }


   protected static IEnumMoniker DeviceEnum(ref Guid Category)
   {
      ICreateDevEnum SysDev = (ICreateDevEnum) COM . CreateInstanceFromType(DirectShowNode . CLSID_SystemDeviceEnum);
      if (null == SysDev)
        return null;

      IEnumMoniker em;
      SysDev . CreateClassEnumerator(ref Category, out em, 0);
      Marshal . ReleaseComObject(SysDev);
      return em;
   }

   /// <summary>
   /// The base filter of the device, used to access most of its features
   /// </summary>
   internal IBaseFilter Filter;

   /// <summary>
   /// The accessor to the various properties of the camera device
   /// </summary>
   protected IPropertyBag Properties;

   internal DirectShowNode(string Name)
   {
      _DisplayName = Name;
   }

   /// <summary>
   /// Creates a filter node
   /// </summary>
   /// <param name="G"></param>
   internal DirectShowNode(Guid G)
   {
      Filter = (IBaseFilter) COM . CreateInstanceFromType(G);
   }

   /// <summary>
   /// Creates the node as a wrapper around the given filter node
   /// </summary>
   /// <param name="Filter"></param>
   protected DirectShowNode(IBaseFilter Filter)
   {
      this . Filter = Filter;
      IPropertyBag Properties = (IPropertyBag)     Filter;
   }

   protected DirectShowNode(IMoniker Moniker)
   {
      // Get the base filter of the device
      Guid G = typeof(IBaseFilter) . GUID;
      object P;
      Moniker . BindToObject( null, null, ref G, out P);
      Filter = (IBaseFilter) P;

      // We have to retrieve the property bag separately since we don't track the moniker
      G = typeof(IPropertyBag) . GUID;
      Moniker . BindToStorage(null, null, ref G, out P);
      Properties = (IPropertyBag)     P;
   }


   ~DirectShowNode()
   {
      Dispose();
   }

   public virtual void Dispose()
   {
      GC . SuppressFinalize(this);
      if (null != Properties && Filter == Properties)
        Marshal . ReleaseComObject(Properties);

      if (null != Filter)
        Marshal . ReleaseComObject(Filter);
   }


   /// <summary>
   /// Tracks the last error code from the DirectShow or Win32 or other p/invoke call
   /// </summary>
   /// <remarks>
   /// 0x80070492 E_PROP_SET_UNSUPPORTED 
   /// 0x80070057 E_INVALIDARG
   /// </remarks>
   protected int _LastError;


   /// <summary>
   /// The displayable name of the device.  Often this is a lot of gibberish.
   /// </summary>
   string _DisplayName;


   /// <summary>
   /// The displayable name of the device.  Often this is a lot of gibberish.
   /// </summary>
   public string DisplayName
   {
      get
      {
         if (null != _DisplayName || null == Properties)
           return _DisplayName;

         object S;
         _LastError = Properties. Read("FriendlyName", out S, null);
         if (null == S)
           return null;
         return _DisplayName = string . Intern((string) S);
      }
   }


   /// <summary>
   /// A description of the device
   /// </summary>
   string _Description;

   /// <summary>
   /// A description of the device
   /// </summary>
   public string Description
   {
      get
      {
         if (null != _Description || null == Properties)
           return _Description;
         object S;
         _LastError = Properties . Read("Description", out S, null);
         if (null == S)
           return null;
         return _Description = string . Intern((string) S);
      }
   }


   /// <summary>
   /// The system device path of this device
   /// </summary>
   string _DevicePath;
   /// <summary>
   /// The system device path of this device
   /// </summary>
   public string DevicePath
   {
      get
      {
         if (null != _DevicePath || null == Properties)
           return _DevicePath;
         object S;
         _LastError =  Properties . Read("DevicePath", out S, null);
         if (null == S)
           return null;
         return _DevicePath = string . Intern((string) S);
      }
   }


   /// <summary>
   /// Information about who made the device
   /// </summary>
   string _VendorInfo;
   /// <summary>
   /// Information about who made the device
   /// </summary>
   public string VendorInfo
   {
      get
      {
         if (null != _VendorInfo || null == Properties)
           return _VendorInfo;
	 _LastError = Filter . QueryVendorInfo(out _VendorInfo);
         if (null != _VendorInfo)
           _VendorInfo = string . Intern(_VendorInfo);
         return _VendorInfo;
      }
   }

   /// <summary>
   /// Get information about the media type of the video source
   /// </summary>
   internal virtual AMMediaType MediaType
   {
      get
      {
         AMMediaType mt = new AMMediaType();
         if (0 == ((ISampleGrabber) Filter) . GetConnectedMediaType(mt))
           return mt;
         mt . Dispose();
         return null;
      }

      set {((ISampleGrabber) Filter) . SetMediaType(value);}
   }

// pinvoke
   [DllImport("oleaut32.dll", PreserveSig = false)]
   static extern void OleCreatePropertyFrame(IntPtr hwndOwner, uint x, uint y,
    [MarshalAs(UnmanagedType.LPWStr)] string lpszCaption,
    UInt32 cObjects,
   [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4, ArraySubType = UnmanagedType.IUnknown)] object[] lplpUnk,
    UInt32 cPages,
    /* [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 6)]*/ IntPtr lpPageClsID,
    uint lcid, UInt32 dwReserved, IntPtr lpvReserved);

   /// <summary>
   /// Display the controls the user can use to tweak the web cam
   /// </summary>
   /// <param name="hWnd"></param>
   /// <returns></returns>
   public IntPtr PropertyPage(IntPtr hWnd)
   {
      // See if it implements a property page
      CAUUID caGUID = new CAUUID();
      ((ISpecifyPropertyPages) Filter) . GetPages(out caGUID);
      if(caGUID . cElems > 0)
        {
           object[] O = new object[]{Filter};
           OleCreatePropertyFrame(hWnd, 30, 30, "Video Parameters", 1,
                                  O, caGUID.cElems,
                                  caGUID.pElems, 0, 0,  IntPtr.Zero);

            Marshal . FreeCoTaskMem(caGUID.pElems);
        }
       return IntPtr . Zero;
   }


const int WS_CHILD = 0x40000000;
const int WS_CLIPCHILDREN = 0x02000000;
const int WS_CLIPSIBLINGS = 0x04000000;

   public void RenderOnto(Control X)
   {
      IVideoWindow Video = (IVideoWindow) Filter;
      Video . put_Owner(X . Handle);
      Video . put_WindowStyle(WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
      PreviewResize(X);
   }


   /// <summary>
   /// 
   /// </summary>
   /// <param name="X"></param>
   public void PreviewResize(Control X)
   {
      IVideoWindow Video = (IVideoWindow) Filter;
      int X0 = X.ClientRectangle.Left;
      int Y0 = X.ClientRectangle.Top;
      int Width = X.ClientRectangle.Right-X0;
      int Height= X.ClientRectangle.Bottom-Y0;
      int H1 = Width * 240 / 320;
      if (H1 < Height)
        Height = H1;
      int W1 = Height * 320 / 240;
      if (W1 < Width)
        Width = W1;
      Video . SetWindowPosition(X0,    Y0,
                                X0+Width, Y0+Height);
   }

}
